$(function() {
	var timeZoneID = $('#hiddenTimeZoneID').val();
	
	// 页面控件
	var $dataTable = $('#dataTable'); // 表格
	var $dataTableToolbar = $('#dataTableToolbar'); // 表格：工具栏
	var $btnAddToggle = $('#btnAddToggle'); // 表格：上传按钮
	var $btnEditToggle = $('#btnEditToggle'); // 表格：修改按钮
	var $btnRemoveToggle = $('#btnRemoveToggle'); // 表格：删除按钮
	var $btnCheckAll = $('#btnCheckAll'); // 表格：全选按钮
	var $btnInvertCheck = $('#btnInvertCheck'); // 表格：反选按钮
	var $btnUncheckAll = $('#btnUncheckAll'); // 表格：取消选择按钮
	
	var $inputName = $('#inputName'); // 查询条件：名称
	var $chosenTypeList = $('#chosenTypeList'); // 查询条件：矿机类型
	
	var $editDialog = $('#editDialog'); // 添加/修改窗口
	var $editDialogLabel = $('#editDialogLabel'); // 添加/修改窗口：标题
	var $editForm = $('#editForm'); // 添加/修改窗口：表单
	var $fileName = $('#fileName'); // 添加/修改窗口：固件文件名
	var $fileNameTip = $('#fileNameTip'); // 添加/修改窗口：未选择文件时的提示信息
	var $minerTypeId = $('#minerTypeId'); // 添加/修改窗口：“矿机类型”下拉列表框
	var $minerTypeIdTip = $('#minerTypeIdTip'); // 添加/修改窗口：未选择矿机类型时的提示信息
	var $name = $('#name');  // 添加/修改窗口：固件名称
	var $version = $('#version'); // 添加/修改窗口：固件版本
	var $remark = $('#remark'); // 添加/修改窗口：备注
	var $btnSave = $('#btnSave'); // 添加/修改窗口：保存按钮
	var $btnReset = $('#btnReset'); // 添加/修改窗口：重置按钮
	
	var uploader; // 文件上传控件
	var uploaderFileChanged = false;
	
	var minerTypeMap = {}; // 矿机类型映射<name, id>
	
	initWidgets();
	initListeners();
	initValidators();
	initUploader();
	
	var formData; // 表单数据
	var saveMode = 0; // 保存方式：1：添加；2：修改
	// 弹出添加窗口时使用的初始表单控件值
	var emptyData = {id:'', minerTypeId:'', name:'', version:'', serial:'', extension:'', remark:''};
	
	// 弹出添加窗口
	function openAddDialog() {
		$editDialogLabel.text('添加固件');
		initFormData(emptyData);
		$editDialog.modal('show');
		saveMode = 1;
	}

	// 弹出修改窗口
	function openEditDialog(data) {
		$editDialogLabel.text('修改固件');
		initFormData(data);
		$editDialog.modal('show');
		saveMode = 2;
	}

	// 弹出删除确认窗口
	function openRemoveDialog(datas) {
		var tableDatas = $dataTable.bootstrapTable('getData');
		var title = '';
		if (datas.length == 1) {
			title = '将删除固件' + datas[0].name + '。';
		} else if(datas.length == tableDatas.length) {
			title = '将删除所有固件。';
		} else {
			title = '将删除所选' + datas.length + '个固件。';
		}
		swal({
	        title: title,
	        type: "warning",
	        showCancelButton: true,
	        cancelButtonText : "让我再考虑一下…",
	        confirmButtonColor: "#ed5565",
	        confirmButtonText : "是的，我要删除！",
	        text: '删除操作无法恢复，请谨慎操作！'
	    }, function(isConfirm) {
			if (isConfirm) {
				doDelete(JSON.stringify(datas));
			}
		});
	}

	// 初始化表单控件的值
	function initFormData(data) {
		uploaderFileChanged = false;
		formData = data;
		$.each(formData, function (key, value) {
			$('#' + key).val(value);
		});
		$fileName.text(data.serial + data.extension);
		initChosenTypeData(data.minerTypeId);
		$name.val(data.name);
		$editForm.validate().form();
	}
	
	// 重置表单
	function doReset() {
		initFormData(formData);
	}

	// 保存（修改或添加）
	function doSave() {
		var data = $editForm.serializeObject();
		//var paramData = JSON.stringify(data);
		if (saveMode == 1) {
			doPost(data);
		} else if (saveMode == 2) {
			doPut(data);
		}
	}

	// 添加
	function doPost(data) {
		uploader.option('formData', {
			firmwareId: -1,
			minerTypeId: data.minerTypeId,
			firmwareName: data.name,
			version: data.version,
			remark: data.remark
		});
		loadmask.showProgress('正在上传，请稍后...');
		uploader.upload();
	}

	// 修改
	function doPut(data) {
		if (uploaderFileChanged) {
			uploader.option('formData', {
				firmwareId: data.id,
				minerTypeId: data.minerTypeId,
				firmwareName: data.name,
				version: data.version,
				serial: data.serial,
				extension: data.extension,
				remark: data.remark
			});
			loadmask.showProgress('正在上传，请稍后...');
			uploader.upload();
		} else {
			loadmask.show('正在修改，请稍后...');
			$.ajax({
				url: 'firmwares',
				type: 'POST',
				dataType: 'json',
				//contentType: "application/json; charset=utf-8",
				data: {
					firmwareId: data.id,
					minerTypeId: data.minerTypeId,
					firmwareName: data.name,
					version: data.version,
					remark: data.remark
				},
				success: function(result) {
					if (result.success) {
						toastr.success(result.message, '修改成功');
						$editDialog.modal('hide');
					} else {
						toastr.error(result.message, '修改失败');
					}
					$dataTable.bootstrapTable('refresh');
					loadmask.hide();
				},
				error: function(request, status, error) {
					toastr.error(error, '异常');
					$dataTable.bootstrapTable('refresh');
					loadmask.hide();
				}
			});
		}
	}

	// 删除
	function doDelete(data) {
		loadmask.show('正在删除，请稍后...');
		$.ajax({
			url: 'firmwares',
			type: 'DELETE',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			data: data,
			success: function(result) {
				if (result.success) {
					toastr.success(result.message, '删除成功');
					$dataTable.bootstrapTable('refresh');
				} else {
					toastr.error(result.message, '删除失败');
				}
				loadmask.hide();
			},
			error: function(request, status, error) {
				toastr.error(error, '异常');
				loadmask.hide();
			}
		});
	}

	function getHeight() {
	    return $(window).height() - 40;
	}
	
	// 初始化表单验证
	function initValidators() {
		var validIcon = "<i class='fa fa-times-circle'></i> ";
		$editForm.validate({
			rules: {
				name: { required: true },
				version: { required: true, firmwareVersion: true },
				remark: { required: false, maxlength: 300 }
			},
			messages: {
				name: validIcon + '请输入固件名称。',
				version: validIcon + '请输入正确的固件版本号，如20150715。',
				remark: validIcon + '备注不能超过300个字符。',
			}
		});
	}
	
	function initListeners() {
		$(window).resize(function () {
			$dataTable.bootstrapTable('resetView', {
	            height: getHeight()
	        });
	    });
		
		// 查询条件：“矿机类型”下拉列表框-值改变时刷新数据表格
		$chosenTypeList.on('change', function() {
			$dataTable.bootstrapTable('refresh');
		});
		// 查询条件：名称-值改变时刷新数据表格
		$inputName.on('change', function() {
			$dataTable.bootstrapTable('refresh');
		});
		
		// 添加/修改窗口：“矿机类型”下拉列表框-值改变时显示或隐藏提示信息
		$minerTypeId.on('change', function() {
			if (!$minerTypeId.val()) {
				$minerTypeIdTip.show();
			} else {
				$minerTypeIdTip.hide();
			}
		});
		// 添加/修改窗口：保存按钮
		$btnSave.on('click', function() {
			var valid = $editForm.validate().form();
			if (!$fileName.text()) {
				valid &= false;
				$fileNameTip.html('<i class="fa fa-times-circle"></i> 请选择固件文件！');
				$fileNameTip.show();
			} else {
				$fileNameTip.hide();
			}
			if (!$minerTypeId.val()) {
				valid &= false;
				$minerTypeIdTip.show();
			}else {
				$minerTypeIdTip.hide();
			}
			if (!valid) {
				return;
			}
			doSave();
		});
		// 添加/修改窗口：重置按钮
		$btnReset.on('click', function() {
			doReset();
		});
		
		// 表格：添加按钮
		$btnAddToggle.on('click', function() {
			openAddDialog();
		});
		// 表格：修改按钮
		$btnEditToggle.on('click', function() {
			var selections = $dataTable.bootstrapTable('getSelections');
			if (selections.length == 0) {
				toastr.warning('请选择一个要修改的固件。', '提示');
				return;
			} else if (selections.length > 1) {
				toastr.warning('只能选择一个固件进行修改。', '提示');
				return;
			}
			openEditDialog(selections[0]);
		});
		// 表格：删除按钮
		$btnRemoveToggle.on('click', function() {
			var selections = $dataTable.bootstrapTable('getSelections');
			if (selections.length == 0) {
				toastr.warning('请选择要删除的固件。', '提示');
				return;
			}
			openRemoveDialog(selections);
		});
		// 表格：全选按钮
		$btnCheckAll.on('click', function() {
			$dataTable.bootstrapTable('checkAll');
		});
		// 表格：反选按钮
		$btnInvertCheck.on('click', function() {
			var datas = $dataTable.bootstrapTable('getData');
			for (var i=0; i<datas.length; i++) {
				if (datas[i].checkStatus) {
					$dataTable.bootstrapTable('uncheck', i);
				} else {
					$dataTable.bootstrapTable('check', i);
				}
			}
		});
		// 表格：取消选择按钮
		$btnUncheckAll.on('click', function() {
			$dataTable.bootstrapTable('uncheckAll');
		});
	}
	
	// 查询条件 和 添加/修改窗口 中的 “矿机类型”下拉列表框-添加数据
	function initChosenTypeData(selection) {
		$.ajax({
			url: 'types',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(result) {
				if (result.success) {
					minerTypeMap = {};
					$chosenTypeList.empty();
					$minerTypeId.empty();
					$chosenTypeList.append($('<option></option>').val('').html(''));
					$minerTypeId.append($('<option></option>').val('').html(''));
					var allDatas = result.rows;
					for (var i = 0; i < allDatas.length; i++) {
						var data = allDatas[i];
						minerTypeMap[data.name] = data.id;
						$chosenTypeList.append($('<option></option>').val(data.id).html(data.name));
						$minerTypeId.append($('<option></option>').val(data.id).html(data.name));
					}
					$minerTypeId.val(selection);
					$chosenTypeList.chosen('destroy').chosen({allow_single_deselect: true, width:'100px'});
					$minerTypeId.chosen('destroy').chosen({allow_single_deselect: true, width:'100%'});
				} else {
					toastr.error(result.message, '矿机类型下拉列表数据获取失败');
				}
			},
			error: function(request, status, error) {
				toastr.error(error, '矿机类型下拉列表数据获取失败');
			}
		});
	}
	
	// 初始化页面控件
	function initWidgets() {
		// 查询条件：矿机类型下拉列表框
		$chosenTypeList.chosen({allow_single_deselect: true, width:'100px'});
		// 添加/修改窗口：“矿机类型”下拉列表框-初始化
		$minerTypeId.chosen({allow_single_deselect: true, width:'100%'});
		// 查询条件 和 添加/修改窗口 中的 “矿机类型”下拉列表框-添加数据
		initChosenTypeData('');
		
		// 表格
		$dataTable.bootstrapTable({
			height: getHeight(),
			url: 'firmwares',
			queryParams: function(params) { // 构建表格查询参数
				var minerTypeId = $chosenTypeList.val();
				var name = $inputName.val();
				var params = {
								minerTypeId: minerTypeId,
								name: name,
								sort: params.sort,
								order: params.order
							};
				return params;
			},
			idField: 'id',
			//clickToSelect: true,
			pagination: false,
			sidePagination: 'server',
			showRefresh: true,
			showToggle: true,
			showColumns: true,
			toolbar: '#dataTableToolbar',
			iconSize: 'outline',
			icons: {
				paginationSwitchDown: 'glyphicon-collapse-down icon-chevron-down',
	            paginationSwitchUp: 'glyphicon-collapse-up icon-chevron-up',
	            refresh: 'glyphicon-repeat',
				toggle: 'glyphicon-list-alt',
				columns: 'glyphicon-list',
	            detailOpen: 'glyphicon-plus icon-plus',
	            detailClose: 'glyphicon-minus icon-minus'
			},
			editable: true,
			onEditableSave: function(field, row, oldValue, $el) {
				uploaderFileChanged = false;
				doPut(JSON.stringify(row));
			},
			columns: [
				{
					field: 'checkStatus',
					checkbox: true,
					align: 'center'
				},
				{
					field: 'id',
					title: 'ID',
					align: 'center',
					sortable: true,
					visible: false
				},
				{
					field: 'name',
					title: '固件名称',
					halign: 'center',
					align: 'left',
					sortable: true,
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!value) {
								return '请输入固件名称。';
							}
							return '';
						}
					}
				},
				{
					field: 'version',
					title: '固件版本',
					align: 'center',
					sortable: true,
				},
				{
					field: 'minerTypeName',
					title: '矿机类型',
					halign: 'center',
					align: 'left',
				},
				{
					field: 'serial',
					title: '固件文件序列（文件名）',
					halign: 'center',
					align: 'right',
				},
				{
					field: 'extension',
					title: '固件文件类型',
					halign: 'center',
					align: 'left',
				},
				{
					field: 'remark',
					title: '备注',
					halign: 'center',
					align: 'left',
					editable: {
						type: 'text',
						validate: function(value) {
							value = $.trim(value);
							if (!value && value.length > 300) {
								return '备注不能超过300个字符。';
							}
							return '';
						}
					}
				},
				{
					field: 'insertTime',
					title: '上传时间',
					align: 'center',
					sortable: true,
					formatter: function(value, row, index) {
						return moment.tz(value, timeZoneID).format('YYYY-MM-DD HH:mm:ss') + '(' + timeZoneID + ')';
					}
				},
				{
					field: 'operate',
					title: '操作',
					align: 'center',
					events: window.operateEvents = {
							'click .edit': function (e, value, row, index) {
								openEditDialog(row);
					        },
					        'click .delete': function (e, value, row, index) {
					        	var rows = new Array(1);
					        	rows[0] = row;
					        	openRemoveDialog(rows);
					        }
					},
					formatter: function(value, row, index) {
						return [
								'<a class="edit" href="javascript:void(0)" title="修改">',
								'<i class="glyphicon glyphicon-edit"></i>',
								'</a>  ',
								'<a class="delete" href="javascript:void(0)" title="删除">',
								'<i class="glyphicon glyphicon-remove"></i>',
								'</a>'
						       ].join('');
					}
				}
			]
		});
	}
	
	// 设置文件上传控件按钮尺寸
	function initUploaderSize() {
		var children = $('#btnFilePicker').children();
		for (var i = 0; i < children.length; i++) {
			$(children[i]).css({width:82, height:38});
		}
	}
	
	// 初始化文件上传
	function initUploader() {
		var fileLimit = 100 * 1024 * 1024; // 100 M
	    uploader = WebUploader.create({
	    	swf: '../js/plugins/webuploader/Uploader.swf',
			server: 'firmwares',
			method: 'POST',
	    	pick: {
	    		id: '#btnFilePicker',
	    		multiple: false
	    	},
	        disableGlobalDnd: true,
	        fileNumLimit: 1,
	        fileSizeLimit: fileLimit,
	        fileSingleSizeLimit: fileLimit,
	        accept: {
	        	title: 'Firmware',
	        	extensions: 'gz,tar',
	        	mimeTypes: 'application/*'
	        }
	    });
	    
	    initUploaderSize();
	    
	    uploader.on('fileQueued', function(file) {
	    	var fileName = file.name;
	    	$fileName.text(fileName);
	    	$fileNameTip.hide();
	    	var name = fileName.substring(0, fileName.indexOf('.'));
	    	$name.val(name);
	    	var parts = name.split('-');
	    	if (parts == null || parts.length == 0) {
	    		return;
	    	}
	    	if (parts.length >= 3) {
	    		var type = parts[1];
	    		var version = parts[2];
	    		var typeId = minerTypeMap[type];
	    		$minerTypeId.val(typeId);
	    		$minerTypeId.chosen('destroy').chosen({allow_single_deselect: true, width:'100%'});
	    		$version.val(version);
	    	}
	    	uploaderFileChanged = true;
	    });
	    
	    uploader.on('beforeFileQueued', function(file) {
	    	uploader.reset();
	    	return true;
	    });
	    
	    uploader.on('error', function(error) {
	    	if ('Q_EXCEED_SIZE_LIMIT' == error) {
	    		$fileNameTip.html('<i class="fa fa-times-circle"></i> 固件文件大小不能超过100M！');
	    		$fileNameTip.show();
	    	}
	    	if ('Q_TYPE_DENIED' == error) {
	    		$fileNameTip.html('<i class="fa fa-times-circle"></i> 请选择正确的文件类型：.tar或.gz！');
	    		$fileNameTip.show();
	    	}
	    });
	    
	    uploader.on('uploadProgress', function(file, percentage) {
	    	loadmask.updateProgress(percentage);
	    });
	    
	    uploader.on('uploadSuccess', function(file, result) {
	    	if (result.success) {
	    		toastr.success(result.message, '上传成功');
				$dataTable.bootstrapTable('refresh');
				$editDialog.modal('hide');
	    	} else {
	    		toastr.error(result.message, '上传失败');
	    	}
	    });
	    
	    uploader.on('uploadError', function(file, reason) {
	    	toastr.error(reason, '上传失败');
	    });
	    
	    uploader.on('uploadComplete', function(file) {
	    	uploader.reset();
	    	loadmask.hide();
	    });
	}
});